package fu.capstone.hanoicityguide.presentation.fragment.food;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.food.FoodBO;
import fu.capstone.hanoicityguide.business.bo.food.FoodBOImp;
import fu.capstone.hanoicityguide.business.model.Food;
import fu.capstone.hanoicityguide.presentation.adapter.ListFoodAdapter;

@SuppressLint("ValidFragment")
public class ListFoodFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private FoodBO foodBO;
	private ArrayList<Food> arrFood;
	private SearchView searchView;
	private DrawerLayout drawer;
	private String sorter;
	private String keyword;
	private ListFoodAdapter foodAdapter;

	public ListFoodFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// inflate layout for ListFoodFragment
		View listFoodFragment = null;
		try {
			setHasOptionsMenu(true);

			listFoodFragment = inflater.inflate(R.layout.fragment_list_food,
					container, false);

			foodBO = new FoodBOImp(container.getContext());

			ListView listFood = (ListView) listFoodFragment
					.findViewById(R.id.listFood);

			arrFood = new ArrayList<Food>();

			// set sorter
			setSorter(getResources().getStringArray(R.array.sorter_items)[0]);
			// set keyword
			setKeyword("");

			arrFood = foodBO.listFood(getSorter());
			foodAdapter = new ListFoodAdapter(getActivity(),
					R.layout.adapter_list_food, arrFood);

			listFood.setAdapter(foodAdapter);

			listFood.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Fragment browseFood = new DetailFoodFragment(arrFood.get(
							position).getId());
					if (browseFood != null) {
						FragmentManager fragmentManager = getFragmentManager();
						FragmentTransaction fTransaction = fragmentManager
								.beginTransaction();
						fTransaction.addToBackStack(null);
						fTransaction.replace(R.id.frame_container, browseFood)
								.commit();
						getActivity().setTitle(arrFood.get(position).getName());
						// update selected item and title, then close the drawer
					}
				}
			});
		} catch (Exception e) {
			Log.e("ListFoodFragment : ", e.toString());
		}

		return listFoodFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_food_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_food)
				.getActionView();
		setupSearchView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;
		switch (item.getItemId()) {
		// click on sort item
		case R.id.action_sort_food:
			builder.setTitle("Sort");
			builder.setItems(getResources()
					.getStringArray(R.array.sorter_items),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int item) {
							// sort by sorter
							setSorter(getResources().getStringArray(
									R.array.sorter_items)[item]);
							if ("".equals(getKeyword())) {
								arrFood = foodBO.listFood(getSorter());
							} else {
								arrFood = foodBO.searchFood(getKeyword(),
										getSorter());
							}
							// reset array attraction in adapter
							foodAdapter.setArr(arrFood);
							foodAdapter.notifyDataSetChanged();
						}
					});
			dialog = builder.create();
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Food Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// invoke when searchView has change focus
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else if (!hasFocus) {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getActivity().getActionBar().setTitle("Foods");
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getSorter() != null) {
			arrFood = foodBO.searchFood(getKeyword(), getSorter());
			foodAdapter.setArr(arrFood);
			foodAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);
		if (getKeyword() != null && getSorter() != null) {
			arrFood = foodBO.searchFood(getKeyword(), getSorter());
			foodAdapter.setArr(arrFood);
			foodAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		searchView.setQuery("", true);
		setKeyword("");
		arrFood = foodBO.listFood(getSorter());
		foodAdapter.setArr(arrFood);
		foodAdapter.notifyDataSetChanged();
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

	public DrawerLayout getDrawer() {
		return drawer;
	}

	public void setDrawer(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	public String getSorter() {
		return sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

}
